package de.unistuttgart.iaas.interaction.mail;

import java.io.IOException;
import java.util.Properties;

import javax.mail.*;

import org.apache.log4j.Logger;

import de.unistuttgart.iaas.interaction.mail.util.ConfigFileHandler;

/** 
 * This class creates the connection to administrator's mail account.
 * @author Lina Sun
 *
 */
public class AdminConnector 
{
	private static Logger logger = Logger.getLogger(AdminConnector.class);
	
	/**
	 * This method creates session object for sending a mail.
	 * @param config -- get parameters for session, for example, Host,Port,username, password
	 * @return Session
	 */
	public static Session SendConnector(ConfigFileHandler config)
	{
		Session session = null;
    	String sendHost = config.getSendHost();
    	String username = config.getUsername();
    	String password = config.getPassword();
    	int sendPort = config.getSendPort();
    	try
    	{
		    Authenticator auth = new MailAuthenticator(username,password); 
		    
		    // create properties
		    Properties properties = System.getProperties();
	
		    // set hostname for properties
		    properties.setProperty("mail.smtp.host", sendHost);
	
		    // set port for properties
		    properties.setProperty("mail.smtp.port", String.valueOf(sendPort)); 
	
		    // In general, authentication information will be asked, 
		    //so this will be set in the properties 
		    properties.setProperty("mail.smtp.auth", "true");
		    
		    properties.put("mail.transport.protocol", "smtp");
	
		    // create a new Session object
		    session = Session.getDefaultInstance(properties,auth);
		    
		    
    	}
    	catch(Exception exSendConnError)
    	{
    		logger.error("Connection for send fails.");
    	}
    	
    	return session;
	}
	
	/**
	 * This method creates session object for receiving a mail.
	 * @param config -- get parameters for session, for example, username, password
	 * @return Session
	 */
	public static Session recieveConnector(ConfigFileHandler config)
	{
		Session session = null;
//		String adminAddress = config.getMailAddress();
//    	String recieveHost = config.getRecieveHost();
     	String username = config.getUsername();
    	String password = config.getPassword();
//    	int recievePort = config.getRecievePort();
		try
		{
			Authenticator auth = new MailAuthenticator(username,password); 
			
	    	// Get hold of the default session 
	    	Properties props = System.getProperties();
	    	session = Session.getDefaultInstance(props, auth);
			
		}
		catch(Exception exRecieveConnError)
		{
			logger.error("Connection for recieve fails.");
		}
		
		return session;
	}
		
}
